package com.minglead.crawler.schedule;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.minglead.crawler.base.ActionResult;
import com.minglead.crawler.entity.YqCrawlerEntity;
import com.minglead.crawler.exception.BizCommonException;
import com.minglead.crawler.feign.PriceFeignClient;
import com.minglead.crawler.service.YqCrawlerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @description: 更新媒体状态定时任务
 * @author: tzf
 * @date: 2024-1-7
 **/
@Configuration
@EnableScheduling
public class YqCrawlerUpdateStateTask extends ScheduledTaskCommon {

    @Autowired
    private PriceFeignClient priceFeignClient;

    @Autowired
    private YqCrawlerService yqCrawlerService;

    @Override
    public String getCron() {
        return "0 */2 * * * ?";
    }//每两分钟执行一次


    @Override
    @Transactional
    public void execute() {
        ActionResult actionResult = priceFeignClient.listCrawlerState();
        if(actionResult.getCode() != 200){
            throw new BizCommonException("获取状态出错");
        }
        List<YqCrawlerEntity> crawlerEntityList = JSON.parseArray(JSON.toJSONString(((Map<String, Object>)actionResult.getData()).get("data")), YqCrawlerEntity.class);
        for (YqCrawlerEntity entity : crawlerEntityList) {
            LambdaUpdateWrapper<YqCrawlerEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(YqCrawlerEntity::getName, entity.getName())
                    .set(YqCrawlerEntity::getState, entity.getState());
            yqCrawlerService.update(updateWrapper);
        }
        System.out.println("更新媒体状态定时任务结束，媒体状态更新成功。");
    }
}
